package tyk.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tyk.common.JwtUtil;
import tyk.common.MyException;
import tyk.vo.UserVo;
import tyk.mapper.UserMapper;
import tyk.pojo.User;
import tyk.service.UserService;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.util.DigestUtils.md5DigestAsHex;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private JwtUtil jwtUtil;

    /*
    * 用户登录
    * */

    @Override
    public UserVo login(User user) {

        user.setPassWord(md5DigestAsHex(user.getPassWord().getBytes())); //密码进行md5加密，和数据库中密码进行比对
        User userFromMysql = lambdaQuery()                                           //数据库中存的全是密码经过md5加密的字符串
                .eq(User::getUserName, user.getUserName())
                .eq(User::getPassWord, user.getPassWord())
                .one();

        if (userFromMysql == null)
            throw new MyException("账号或者密码错误");
        System.out.println(userFromMysql);
        lambdaUpdate()                                                              //修改上次登录时间
                .set(User::getLastTime, LocalDateTime.now())
                        .eq(User::getId, userFromMysql.getId())
                                .update();

        userFromMysql.setPassWord("******");                                         //尽量不给前端返回密码重要信息

        UserVo userDto = BeanUtil.copyProperties(userFromMysql, UserVo.class);     //属性拷贝，将userFromMysql中相同的属性拷贝给userDto对象

        Map<String,Object> map = new HashMap<>();
        map.put("userId",userDto.getId());
        String token = jwtUtil.generateJwtToken(map);                                 //获得jwt令牌
        userDto.setToken(token);


        return userDto;
    }
}
